# -*- encoding: utf-8 -*-
"""
@File: constants.py
@Author: cyl
"""
import threading
from faker import Faker
from common.my_types import Any
from common.my_db import MyPickledb
from utils.db_handler import DBHandler
from utils.assert_handle import Assertion
from utils.requests_handle import RequestHandle
from setting import (
    UseMySQL,
    MysqlHost,
    MysqlPort,
    MysqlUser,
    MysqlPwd,
    MysqlDefaultDB
)


class ApiCaseRevolution(RequestHandle, Assertion):
    __instance = {}
    lock = threading.Lock()
    faker = Faker("zh_CN")

    def __new__(cls, *args, **kwargs):
        if cls.__instance:
            return cls.__instance
        with cls.lock:
            if not cls.__instance:
                cls.__instance = super().__new__(cls)
        return cls.__instance

    def __init__(self):
        self.methods: list = [
            "get",
            "post",
            "put",
            "patch",
            "delete",
            "options"
        ]
        self.pickledb = MyPickledb().my_db

    def __len__(self):
        return len(self.pickledb.getall())

    @staticmethod
    def sql_query(sql: str, one: bool = True) -> Any:
        """rewrite db handler method"""
        if not UseMySQL:
            return None
        mysqldb: DBHandler = DBHandler(
            host=MysqlHost,
            port=MysqlPort,
            user=MysqlUser,
            password=MysqlPwd,
            database=MysqlDefaultDB,
            charset="utf8"
        )
        return mysqldb.query(sql=sql, one=one)

    def get(self, key: str):
        return self.pickledb.get(key)

    def set(self, key: str, value: Any):
        self.pickledb.set(key, value)

    def has(self, key: str):
        return self.pickledb.exists(key)

    def delete(self, key: str, is_delete_all: bool = False):
        self.pickledb.deldb() if is_delete_all else self.pickledb.drem(key)


apb: ApiCaseRevolution = ApiCaseRevolution()
apb_addr: int = id(apb)
